/**
 * 全站http配置
 *
 * header参数说明
 * serialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import {
  Message
} from 'element-ui'


let Base64 = require('js-base64').Base64

axios.defaults.timeout = 30000
const G = window.g
if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = G.url
} else {
  axios.defaults.baseURL = "https://api.xiaozhucaishui.com"
}

// 返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
axios.interceptors.request.use((config) => {
  // console.log(config);
  // NProgress.start() // start progress bar
  // const isToken = (config.headers || {}).isToken === false
  // function getCookie(token){
  //   let strCookie = document.cookie;//获取cookie字符串
  //   let arrCookie = strCookie.split("; ");//分割
  //   //遍历匹配
  //   for ( let i = 0; i < arrCookie.length; i++) {
  //     let arr = arrCookie[i].split("=");
  //     if (arr[0] == "token"){
  //       token = arr[1]
  //     }
  //   }
  //   return token;
  // }
  // let cookie = getCookie()
  // let token = Base64.decode(cookie);
  // window.localStorage.setItem("Authorization", token)
  // config.headers['Authorization'] = token
  // config.url = config.url + '?Authorization=' + token
  //
  // config.url = config.url + '?Authorization=11111111'
  let token = window.localStorage.getItem('token')
  if (token) {
    config.headers['token'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// HTTPresponse拦截
axios.interceptors.response.use((res) => {
  NProgress.done()
  const status = Number(res.status) || 1
  const message = res.data.message
  if (res.data.code === 506 || res.data.code === 507) {
    console.log("进入506")
    Message({
      message: res.data.message,
      type: 'error'
    })
    return
  }
  if (res.status === 401) {
    location.replace("/#/login");
    return
  }

  if (res.data.code !== 1) {
    Message({
      message: res.data.message ? res.data.message : res.data.msg,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  return res
}, error => {
  NProgress.done()
  return Promise.reject(new Error(error))
})



export default axios